package com.woniuxy.commons.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.utile.Result;
import com.woniuxy.controller.dto.AccountDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class LoginErrorHandler implements AuthenticationFailureHandler {

    private ObjectMapper om = new ObjectMapper();

    @Resource
    private StringRedisTemplate srt;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");

        //获取到登录的账号
        String account = request.getParameter("username");

//        Long num = srt.opsForHash().increment("account", "account" + account, 1);
        Long num = srt.opsForValue().increment("account" + account, 1);
        System.out.println(num);
        if (num>=5){
            srt.opsForValue().setIfAbsent("account:"+account,account,1,TimeUnit.DAYS);
        }

        Result result = Result.instance().setMessage(exception.getMessage() == null ?
                "账号或则密码错误" :
                exception.getMessage())
                .setCode(500);
        String json = om.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}
